package net.wicp.tams.common.binlog.parser;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class AssitWrite {
	private final byte[] buff;
	private int curPos = 0;

	public AssitWrite(int size) {
		buff = new byte[size];
	}

	public static void reverse(final byte[] array) {
		if (array == null) {
			return;
		}
		reverse(array, 0, array.length);
	}

	public static byte[] toByteArray(int num) {
		final byte[] r = new byte[4];
		for (int i = 0; i < 4; i++) {
			r[i] = (byte) (num >>> (24 - i * 8));
		}
		return r;
	}

	public static byte[] toByteArray(long num) {
		final byte[] r = new byte[8];
		for (int i = 0; i < 8; i++) {
			r[i] = (byte) (num >>> (56 - i * 8));
		}
		return r;
	}

	public static void reverse(final byte[] array, int startIndexInclusive, int endIndexExclusive) {
		if (array == null) {
			return;
		}
		int i = startIndexInclusive < 0 ? 0 : startIndexInclusive;
		int j = Math.min(array.length, endIndexExclusive) - 1;
		byte tmp;
		while (j > i) {
			tmp = array[j];
			array[j] = array[i];
			array[i] = tmp;
			j--;
			i++;
		}
	}
	public static byte[][] splitBytes(byte[] data, int maxLength) {
		if (data.length <= maxLength) {
			return new byte[][] { data };
		} else {
			int length = data.length / maxLength + 1;
			byte[][] retary = new byte[length][maxLength];
			for (int l = 0; l < data.length; l++) {
				int i = l / maxLength;
				int j = l % maxLength;
				retary[i][j] = data[l];
			}
			return retary;

		}
	}

	/***
	 * 实现小端字节写法,true
	 * 
	 * @param data
	 * @param leng
	 */
	public void writeByte(byte[] data, int leng, boolean littleEndian) {
		if (littleEndian) {
			reverse(data);
		}
		int copylen = data.length > leng ? leng : data.length;
		for (int i = 0; i < copylen; i++) {
			buff[curPos + i] = data[i];
		}
		curPos = curPos + leng;
	}

	public void write(byte[] data) {
		writeByte(data, data.length, false);
	}

	public void write(int data, int leng) {
		writeByte(toByteArray(data), leng, true);
	}

	public void write(long data, int leng) {
		writeByte(toByteArray(data), leng, true);
	}

	public void write(String data, int leng) {
		try {
			writeByte(data.getBytes("UTF-8"), leng, false);
		} catch (UnsupportedEncodingException e) {
		}
	}

	public void write(String data) {
		write(data, data.length());
	}

	public void writeEndNull(byte[] data) {
		write(data);
		write(0, 1);
	}

	public byte[] get() {
		return Arrays.copyOf(buff, curPos);
	}

}
